package com.gitee.ywj1352.test.observer.mouse;

import com.gitee.ywj1352.test.observer.core.EventListener;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by wenjie.yang on 4/1/2019.
 */
public class MouseProxy  implements InvocationHandler {

  private Mouse mouse;

  private EventListener listener;

  public Object getInstance(Mouse mouse,EventListener listener){
    this.mouse = mouse;
    this.listener = listener;
    Class<?> clazz = mouse.getClass();
    return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //proxy 就是返回 this
    /**
     * 比如 假设 有
     * Mouse getHa(){
     *   return this;
     * }
     * 的方法的时候可以使用 proxy return
     */

    System.out.println("代理对象是:"+proxy.getClass());
    //这里的对象是 是代理对象
    Object invoke = method.invoke(this.mouse, args);
    if (method.getName().equals("click")){
      listener.trigger(MouseEventType.ON_CLICK);
    }else if(method.getName().equals("doubleClick")){
      listener.trigger(MouseEventType.ON_DOUBLE_CLICK);
    }else if(method.getName().equals("up")){
      listener.trigger(MouseEventType.ON_UP);
    }
    return invoke;
  }
}
